<template>
  <div id="app" style="overflow: hidden;width:100%;height:100%;">
    <vxe-grid ref="xGrid" v-bind="grid_options" :row-config="{height:36}">
    </vxe-grid>
    <godownEntry ref="godownEntry" @closeEvent="closeEvent"></godownEntry>
    <auditEquipment ref="auditEquipment" @closeShEvent="closeShEvent"></auditEquipment>
    <equipmentList ref="equipmentList" @closeShEvent="closeShEvent"></equipmentList>
  </div>


</template>

<script>
import godownEntry from './components/godownEntry.vue'
import auditEquipment from './components/auditEquipment.vue'
import equipmentList from './components/equipmentList.vue'
import {godownEntryApi} from "@/api/equip/godownEntryApi";
import {warehouseManagement} from '@/api/equip/warehouseManagement.js'
import {CommonApi} from '@/api/equip/CommonApi'
import util from '@/utils/util'
import {getInfo} from "@/api/login";
import {listDept} from "@/api/system/dept";
import VXETable from "vxe-table";

export default {
  name: 'godownEntryListIndex',
  components: {godownEntry, auditEquipment, equipmentList},
  data() {
    return {
      grid_options: {
        border: true,
        stripe: true,
        showHeaderOverflow: false,
        showOverflow: true,
        keepSource: true,
        id: 'full_edit_1',
        height: 700,
        rowId: 'id',  //指定记录主键
        rowConfig: {
          isHover: true
        },
        columnConfig: {
          resizable: true
        },
        customConfig: {
          storage: true,
          // checkMethod: this.checkColumnMethod
        },
        sortConfig: {
          trigger: 'cell',
          remote: true
        },
        filterConfig: {
          remote: true
        },
        formConfig: {
          form: true, // 启用表单代理
          size: "medium",        //尺寸
          titleAlign: "right",  //所有项的标题对齐方式
          titleWidth: "120", //标题宽度
          titleColon: true,     //是否显示标题冒号
          items: [
            {
              field: 'ssdwbm',
              title: '单位:',
              span: 6,
              itemRender: {
                name: '$select',
                options: [],
                props: {placeholder: '---请选择单位---'},
                events: {change: this.gldwbmChangeEvent}
              },
            },
            {
              field: 'id',
              title: '入库单号:',
              span: 6,
              itemRender: {name: '$input', props: {placeholder: '请输入入库单号'}},
            },
            {
              field: 'djshzt',
              title: '单据状态:',
              span: 6,
              itemRender: {name: '$select', options: [], props: {placeholder: '---请选择设备状态---'}}
            },
            {
              field: 'ckbm',
              title: '仓库名称:',
              span: 6,
              itemRender: {name: '$select', options: [], props: {placeholder: '---请选择仓库名称---'}},
              folding: true,
            },
            {
              field: 'djrq',
              title: '入库时间',
              span: 6,
              itemRender: {name: '$input', props: {type: 'datetime'}},
              folding: true,
            },
            {
              field: 'djrq_to',
              title: '至',
              span: 6,
              itemRender: {name: '$input', props: {type: 'datetime'}},
              folding: true,
            },
            {
              span: 6, collapseNode: true, align: 'right', itemRender: {
                name: '$buttons', children: [
                  {props: {type: 'submit', content: '查询', status: 'primary', icon: 'fa fa-search'}},
                  {props: {type: 'reset', content: '重置', icon: 'fa fa-reply'}},
                ]
              }
            }
          ]
        },
        toolbarConfig: {
          buttons: [
            // { buttonRender: { name: 'add', events: { click: this.addRowModal } } }, // 新增
            // { buttonRender: { name: 'edit', events: { click: this.editRowModal } } },//编辑
            // { buttonRender: { name: 'delete', events: { click: this.handleDelete } } },//删除
            // { buttonRender: { name: 'auditall', events: { click: this.handleAuditall } } },//批量审核
            // { buttonRender: { name: 'auditpass', events: { click: this.handleAuditPass } } },//审核
          ],
          refresh: true,
          custom: true,
        },
        pagerConfig: {
          pageSize: 10,
          pageSizes: [5, 10, 15, 20, 50, 100],
          layouts: ['PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total'],
          background: true,
        },
        proxyConfig: {
          seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
          sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
          filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
          form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
          // 对应响应结果 { result: [], page: { total: 100 } }
          props: {
            result: 'data.records', // 配置响应结果列表字段
            total: 'data.total' // 配置响应结果总页数字段
          },
          // 只接收Promise，具体实现自由发挥
          ajax: {
            // 当点击工具栏查询按钮或者手动提交指令 query或reload 时会被触发
            query: ({page, sorts, filters, form}) => {
              // =====给表单项赋初始值======
              this.initFormData(form);
              //    this.enableDefault = false;
              const queryParams = Object.assign({}, form)
              // const queryParams = this.initFormData(form)
              // 处理排序条件
              const firstSort = sorts[0]
              if (firstSort) {
                queryParams.sort = firstSort.property
                queryParams.order = firstSort.order
              }
              // 处理筛选条件

              filters.forEach(({property, values}) => {
                queryParams[property] = values.join(',')
              })
              return this.queryData(page, queryParams)
            },
          }
        },
        columns: [
          {type: 'seq', title: '序号', width: "60px", align: 'center', headerAlign: 'center'},
          // { type: 'checkbox', width: "60px", align: 'center', headerAlign: 'center',visible:true},
          // { field: 'audit', title: '操作', minWidth: "120px", align: 'center', headerAlign: 'center', cellRender: {name: 'audit', events: {click: this.handleAudit}}},
          {field: 'ssdwmc', title: '单位', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {
            field: 'id',
            title: '入库单号',
            minWidth: "160px",
            align: 'center',
            headerAlign: 'center',
            cellRender: {name: 'rkdh', events: {click: this.handleAuditPass}}
          },
          {field: 'djrq', title: '入库日期', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {
            field: 'sl',
            title: '入库数量',
            minWidth: "160px",
            align: 'center',
            headerAlign: 'center',
            cellRender: {name: 'sl', events: {click: this.handleAuditList}}
          },
          {field: 'djshztmc', title: '单据状态', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {field: 'ckmc', title: '库房名称', minWidth: "160px", align: 'center', headerAlign: 'center'},
          {field: 'shPerson', title: '审核人', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {field: 'shTime', title: '审核时间', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {field: 'shyj', title: '审核意见', minWidth: "100px", align: 'center', headerAlign: 'center',},
        ],
        checkboxConfig: {
          // labelField: 'id',
          reserve: true,
          highlight: true,
          range: true
        },
        editConfig: {
          trigger: 'click',
          mode: 'row',
          showStatus: true
        }
      },
      djztOptions: [],
      rowDjshzt: false
      //  api: 'fetchQueryQueryRwxqByPage',
      // init: true
    }
  },
  computed: {
    options() {
      return {
        djztOptions: this.djztOptions,
        kfOptions: this.kfOptions
      }
    }
  },
  created() {
    this.setReadModel()


  },
  mounted() {

    this.$nextTick(function () {
      this.setTableHeight();
      this.fetchdjztOptions()
      this.fetchgldwOptions()
      // this.getKfOptions()
    })
    window.addEventListener('resize', this.setTableHeight);
  },
  destroyed: function () {
    window.removeEventListener('resize', this.setTableHeight);
  },
  methods: {
    // 高度自适应
    setTableHeight: function () {
      const tableContainer = document.querySelector("#app");
      const height = tableContainer.clientHeight;
      this.grid_options.height = height - 5;
    },
    //查询控制
    setReadModel() { //控制是否显示
      const isRead = util.isReadModel()
      if (isRead) {
        // this.grid_options.toolbarConfig.buttons=[{ buttonRender: { name: 'auditpass', events: { click: this.handleAuditPass } } }]
        this.grid_options.toolbarConfig.buttons = []
        this.grid_options.columns[1].visible = false
      }
    },
    initFormData(form) {
      form = this.headerData
      return form
    },
    fetchdjztOptions() {
      CommonApi.queryDictData('EN_CRK_STATE').then(res => {
        // if (res.code === '200') {
        let optionList = [
          {label: '请选择', value: ''}
        ]
        res.data.forEach((item) => {
          optionList.push({label: item.value, value: item.code})
        })
        this.djztOptions = optionList
        const item = this.$refs.xGrid.getFormItems(2)
        item.itemRender.options = optionList
      })
    },
    fetchgldwOptions() {
      getInfo().then(res => {
        let params = {
          deptId: res.user.dept.deptId,
          parentId: res.user.dept.parentId
        }
        listDept(params).then(res => {
          let optionList = [
            {label: '请选择', value: ''}
          ]
          res.data.forEach((item) => {
            optionList.push({label: item.deptName, value: item.deptId})
          })
          this.djztOptions = optionList
          const item = this.$refs.xGrid.getFormItems(0)
          item.itemRender.options = optionList
        })
      })
    },
    gldwbmChangeEvent(value) {
      warehouseManagement.getKfByGldw(value.data.ssdwbm).then(res => {
        // 修改编辑框
        // const sexColumn = $grid.getColumnByField('sex')
        // sexColumn.editRender.options = sexList
        // 修改查询条件列表
        let optionList = [
          {label: '请选择', value: ''}
        ]
        res.data.forEach((item) => {
          // console.log(item,'item.,,,');
          optionList.push({label: item.kfName, value: item.id})
        })
        const item = this.$refs.xGrid.getFormItems(3)
        item.itemRender.options = optionList
      })
    },
    queryData: (page, formData) => {
      const queryParams = {
        pageSize: page.pageSize,
        pageNo: page.currentPage,
        entity: {
          ssdwbm: formData.ssdwbm ? formData.ssdwbm : null,
          id: formData.id ? formData.id : null,
          djshzt: formData.djshzt ? formData.djshzt : null,
          djrq: formData.djrq ? formData.djrq : null,
          djrq_to: formData.djrq_to ? formData.djrq_to : null,
          ckbm: formData.ckbm ? formData.ckbm : null,
          type: '0'//入库0出库1
        },
        paramsMap: {},
        column: '',
        order: ''
      }
      const isRead = util.isReadModel()
      if (isRead) {
        return godownEntryApi.getShpage(queryParams)
      } else {
        return godownEntryApi.page(queryParams)
      }
    },
    addRowModal() {
      this.$refs.godownEntry.showDialog()
    },
    editRowModal() {
      const rowArr = this.$refs.xGrid.getCheckboxRecords(true);
      if (rowArr && rowArr.length === 1) {
        if (rowArr[0].djshzt === '0' || rowArr[0].djshzt === '20') {
          this.$refs.godownEntry.showDialog(true, rowArr[0])
        } else {
          VXETable.modal.confirm({
            content: '包含待审核或归档状态数据\n请重新选择记录',
            title: '操作异常',
            status: 'error'
          })
        }
      } else {
        VXETable.modal.confirm({content: '有且只能够操作一条记录\n请选择一条记录', title: '操作异常', status: 'error'})
      }
    },
    handleDelete() {
      const rowsArr = this.$refs.xGrid.getCheckboxRecords(true);
      const rowscheck = []
      var isDelete = true
      rowsArr.map(item => {
        if (item.djshzt === '0' || item.djshzt === '20') {
          rowscheck.push(item.id)
        } else {
          isDelete = false
          return isDelete
        }
      })
      if (isDelete) {
        let queryParams = rowscheck
        godownEntryApi.delete(queryParams).then(res => {
          if (res.code === '200') {
            this.$message.success(res.message)
            this.$refs.xGrid.commitProxy('query')
          }
        })
      } else {
        VXETable.modal.confirm({
          content: '包含待审核或归档状态数据\n请重新选择记录',
          title: '操作异常',
          status: 'error'
        })
      }
    },
    handleAuditall() { //批量提交审核的方法
      const rowsArr = this.$refs.xGrid.getCheckboxRecords(true);
      const rowscheck = []
      var isAudit = true
      rowsArr.map(item => {
        if (item.djshzt !== '0') {
          isAudit = false
          return isAudit
        } else {
          rowscheck.push(item.id)
        }
      })
      if (isAudit) {
        let queryParams = rowscheck
        godownEntryApi.submitShByIds(queryParams).then(res => {
          if (res.code === '200') {
            this.$message.success(res.message)
            this.$refs.xGrid.commitProxy('query')
          }
        })
      } else {
        VXETable.modal.confirm({
          content: '包含不可进行提交审核操作数据\n请重新选择记录',
          title: '操作异常',
          status: 'error'
        })
      }
    },
    handleAudit(row) { //提交审核的方法
      const isRead = util.isReadModel()
      if (isRead) {
        this.$refs.auditEquipment.showDialog(true, row.row)
      } else {
        const rowcheck = []
        rowcheck.push(row.row.id)
        let queryParams = rowcheck
        godownEntryApi.submitShByIds(queryParams).then(res => {
          if (res.code === '200') {
            this.$message.success(res.message)
            this.$refs.xGrid.commitProxy('query')
          }
        })
      }
    },
    handleAuditPass(val) {
      this.$refs.godownEntry.showDialog(false, val, true)
    },
    handleAuditList(val) {
      this.$refs.equipmentList.showDialog(true, val)
    },
    closeEvent() {
      this.$refs.xGrid.commitProxy('query')
    },
    closeShEvent() {
      this.$refs.xGrid.commitProxy('query')
    }
  }
}
// 创建一个简单的工具栏-左侧按钮渲染
VXETable.renderer.add('add', {
  renderToolbarButton(h, renderOpts, params) {
    const {events = {}} = renderOpts
    const {button, $table} = params
    return [
      <vxe-button icon="fa fa-plus (alias)" content="创建入库单" onClick={
        () => {
          events.click(button)
        }
      }></vxe-button>
    ]
  }
})

// 创建一个简单的工具栏-左侧按钮渲染
VXETable.renderer.add('edit', {
  renderToolbarButton(h, renderOpts, params) {
    const {events = {}} = renderOpts
    const {button, $table} = params
    return [
      <vxe-button icon="fa fa-edit (alias)" content="修改" onClick={
        () => {
          events.click(button)
        }
      }></vxe-button>
    ]
  }
})
// 创建一个简单的工具栏-左侧按钮渲染
VXETable.renderer.add('delete', {
  renderToolbarButton(h, renderOpts, params) {
    const {events = {}} = renderOpts
    const {button, $table} = params
    return [
      <vxe-button icon="fa fa-times (alias)" content="删除" onClick={
        () => {
          events.click(button)
        }
      }></vxe-button>
    ]
  }
})
//入库编号穿透渲染
VXETable.renderer.add('rkdh', {
  renderDefault(h, renderOpts, params) {
    const {events = {}} = renderOpts
    const {row, column} = params
    return [
      <span style="color:#0000FF;cursor: pointer;" onClick={
        () => {
          events.click(params.row)
        }
      }>{params.row.id}</span>
    ]
  }
})
//入库数量穿透渲染
VXETable.renderer.add('sl', {
  renderDefault(h, renderOpts, params) {
    const {events = {}} = renderOpts
    const {row, column} = params
    return [
      <span style="color:#0000FF;cursor: pointer;" onClick={
        () => {
          events.click(params.row)
        }
      }>{params.row.sl}</span>
    ]
  }
})
// 批量
// 创建一个简单的工具栏-左侧按钮渲染
VXETable.renderer.add('auditall', {
  renderToolbarButton(h, renderOpts, params) {
    const {events = {}} = renderOpts
    const {row, column} = params
    return [
      <vxe-button icon="fa fa-check" content="批量提交" onClick={
        () => {
          events.click(params)
        }
      }></vxe-button>
    ]
  }
})
// 创建一个简单的工具栏-左侧按钮渲染
VXETable.renderer.add('auditpass', {
  renderToolbarButton(h, renderOpts, params) {
    const {events = {}} = renderOpts
    const {button, $table} = params
    return [
      <vxe-button icon="fa fa-check" content="审核" onClick={
        () => {
          events.click(button)
        }
      }></vxe-button>
    ]
  }
})
</script>

<style scoped>

</style>
